﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using QD.Web;
using GL.Tools;
using System.Web.Security;
using Newtonsoft.Json.Linq;
using WAD.Model;
using WAD.DAL;

namespace WAD.WEB.AppCode
{
    public class WxJsWebBase : WebBase
    {
        /// <summary>
        /// 微信js分享票据
        /// </summary>
        private static String jsapiTicket;//获取票据  微信网页分享用到

        public const String WX_APPID = "wx5a48f9c519e4452d";//微信公众平台appid
        public const String WX_SECRET = "0f111452b5a533f9ab02de9ccaf911af";//微信公众平台SECRET
        protected static String temp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        protected String timestamp;//生成签名的时间戳 微信网页分享用到
        protected String nonceStr;//生成签名的随机串 微信网页分享用到
        protected String signature;//签名 微信网页分享用到
        protected String rawUrl;//当前网址  微信网页分享用到
        protected void GetWxSharedInfo()
        {
            if (jsapiTicket == null)
            {
                setTicket();
            }
            rawUrl = Request.Url.AbsoluteUri;
            timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            nonceStr = StringHelper.Random(10);
            signature = GetSha1("jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + rawUrl).ToLower();
        }
        private String GetSha1(String str)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");
        }

        public static bool setTicket()
        {
            String ticket = GetTicket();

            if (ticket == null)
            {
                return false;
            }

            jsapiTicket = ticket;
            return true;
        }


        /// <summary>
        /// 获取票据
        /// </summary>
        /// <returns></returns>
        private static String GetTicket()
        {
            //得到tokenJson字符创
            String tokenJsonStr = HttpTool.GetHttpString("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WX_APPID + "&secret=" + WX_SECRET);


            if (tokenJsonStr == null)
            {
                return null;
            }
            JObject joToken = JObject.Parse(tokenJsonStr);
            if (joToken["access_token"] == null)
            {
                return null;
            }

            //得到微信token
            String accessToken = joToken["access_token"].ToString();

            //得到jsonTicket字符创
            String ticketJsonStr = HttpTool.GetHttpString("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi");

            if (ticketJsonStr == null)
            {
                return null;
            }
            JObject joTicket = JObject.Parse(ticketJsonStr);

            if (joTicket["errcode"].ToObject<Int32>() != 0)
            {
                return null;
            }
            return joTicket["ticket"].ToString();
        }

    }
}